﻿using System.Threading.Tasks;
using SaaS.Core.Authorization;
using Microsoft.AspNetCore.Mvc;
using XCore.Authorization;
using System.Collections.Generic;
using System.Linq;
using XCore.Extensions;
using XCore.Helper;
using SaaS.Core;
using SaaS.Cache.Auths;
using SaaS.Model.Enums;
using Web.System.Services.Systems;
using System;

namespace Web.System.Controllers.Systems
{
    /// <summary>
    /// 用户
    /// </summary>
    [Route("api/system/[controller]/[action]")]
    [ApiController]
    public class AdminController : SystemControllerBase
    {
        private readonly AdminAppService _adminAppService;
        private readonly SystemAuthCacheService _adminCacheService;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="adminAppService"></param>
        public AdminController(AdminAppService adminAppService, SystemAuthCacheService adminCacheService)
        {
            _adminAppService = adminAppService;
            _adminCacheService = adminCacheService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost, Permission(PermissionNames.User_Create)]
        public ActionResult Save([FromForm]int? id, [FromForm]string username, [FromForm]string name, [FromForm]int? roleId)
        {
            if (id.HasValue)
            {
                return Ok(_adminAppService.Edit(id.Value, roleId ?? 0));
            }
            else
            {
                return Ok(_adminAppService.Create(username, name, roleId ?? 0));
            }
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpPost, Permission(PermissionNames.Permission_User)]
        public ActionResult List([FromForm]int? id, [FromForm]string username, [FromForm] UserStatus? status)
        {
            var query = SDC.SystemAdmins.Where(id, c => c.Id == id)
                                        .Where(username, c => c.UserName.Contains(username))
                                        .Where(status, c => c.Status == status);

            return PageResult(query.OrderByDescending(c => c.Id), c => new
            {
                c.Id,
                c.CreationTime,
                c.Name,
                c.Status,
                c.IsDefault,
                c.RoleId,
                c.UserName
            });
        }

        /// <summary>
        /// 获取管理员操作日志
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost, ActionName("logs"), Permission(PermissionNames.Permission_User)]
        public ActionResult Log([FromForm]int? adminId, [FromForm] DateTime? startTime, [FromForm] DateTime? entTime)
        {
            var query = SDC.SystemAdminLogs.Where(adminId, c => c.AdminId == adminId)
                                           .Where(startTime, c => c.CreationTime >= startTime)
                                           .Where(entTime, c => c.CreationTime <= entTime);
            return PageResult(query.OrderByDescending(c => c.CreationTime), c => new
            {
                c.Id,
                c.AdminId,
                c.CreationTime,
                c.IP,
                IPAddress = IPHelper.GetAddress(c.IP),
                c.Message,
                c.Source,
                c.Type,
                c.Duration
            });
        }
        /// <summary>
        /// 获取日志详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}"), Permission(PermissionNames.Permission_User)]
        public ActionResult Log(int id)
        {
            return Ok(SDC.SystemAdminLogs.FirstOrDefault(c => c.Id == id));
        }
        /// <summary>
        /// 获取用户功能权限（图表）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}"), Permission(PermissionNames.Permission_User)]
        public ActionResult Permission(int id)
        {
            var auth = _adminCacheService.GetRolePermission(id).ToArray();
            var permission = PermissionFinder.GetAllPermissionChildren(new PermissionAuthorizationProvider(), new PermissionSystemProvider());
            return Ok(new
            {
                auth,
                permission
            });
        }

        /// <summary>
        /// 用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}"), Permission(PermissionNames.Permission_User)]
        public ActionResult Info(int id)
        {
            //最后登陆时间
            var last = SDC.SystemAdminLogs.Where(c => c.AdminId == id && c.Source == SystemLoggerSource.Login)
                                          .OrderByDescending(c => c.CreationTime).Select(c => c.CreationTime).FirstOrDefault();
            //常用登陆IP地址
            var ips = SDC.SystemAdminLogs.Where(c => c.AdminId == id).GroupBy(c => c.IP).Select(c => new
            {
                Ip = c.Key,
                Address = IPHelper.GetAddress(c.Key)
            }).ToArray();
            var user = SDC.SystemAdmins.Where(c => c.Id == id).Select(c => new
            {
                c.Id,
                c.Name,
                c.UserName,
                Avatar = c.Avatar.GetUrl(),
                c.Status,
                c.CreationTime,
                LastLoginTime = last,
                Ips = ips,
                c.RoleId,
            }).FirstOrDefault();
            return Ok(user);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}"), Permission(PermissionNames.User_Delete)]
        public ActionResult Delete(int id)
        {
            return Ok(_adminAppService.Delete(id));
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        [HttpPost("{id}")]
        public ActionResult ResetPwd(int id)
        {
            return Ok(_adminAppService.ResetPwd(id));
        }
        /// <summary>
        /// 锁定用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("{id}")]
        public ActionResult Lock(int id)
        {
            return Ok(_adminAppService.Lock(id));
        }
        /// <summary>
        /// 解锁
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("{id}")]
        public ActionResult UnLock(int id)
        {
            return Ok(_adminAppService.UnLock(id));
        }
    }
}